<template>
  <view class="content">
    <!-- 用户信息卡片 -->
    <view class="uni-card">
      <view class="uni-flex uni-row">
        <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="uni-avatar" :src="userInfo.avatar || '/static/icons/default-user.png'" mode="aspectFill"></image>
        </button>
        <view class="uni-flex uni-column uni-margin-left">
          <input class="nickname-input" type="nickname" v-model="nickname" :placeholder="userInfo.nickname || userInfo.openid?.substring(0, 6) || '请输入昵称'" @nicknamereview="onNicknameChange" />
          <view class="uni-flex uni-row uni-margin-top-sm">
            <text class="uni-text-gray">{{ userInfo.levelName }}</text>
            <text class="uni-text-gray uni-margin-left-sm">Lv.{{ userInfo.level }}</text>
          </view>
        </view>
      </view>
      <view class="uni-flex uni-row uni-justify-around uni-margin-top">
        <view class="uni-flex uni-column uni-align-center" @click="goToPoints">
          <text class="uni-h4">{{ userInfo.points }}</text>
          <text class="uni-text-gray">积分</text>
        </view>
        <view class="uni-flex uni-column uni-align-center" @click="goToCoupon">
          <text class="uni-h4">{{ couponCount }}</text>
          <text class="uni-text-gray">优惠券</text>
        </view>
      </view>
    </view>

    <!-- 我的订单 -->
    <view class="order-section">
      <view class="section-header">
        <text class="section-title">我的订单</text>
        <view class="view-all" @click="goToOrderList(0)">
          <text>查看全部</text>
          <text class="arrow">></text>
        </view>
      </view>
      <view class="order-types">
        <view class="order-type" @click="goToOrderList(1)">
          <view class="icon-wrapper">
            <text class="uni-icons">💰</text>
            <text class="badge" v-if="orderCounts.pending > 0">{{ orderCounts.pending }}</text>
          </view>
          <text class="type-name">待付款</text>
        </view>
        <view class="order-type" @click="goToOrderList(2)">
          <view class="icon-wrapper">
            <text class="uni-icons">🍲</text>
            <text class="badge" v-if="orderCounts.processing > 0">{{ orderCounts.processing }}</text>
          </view>
          <text class="type-name">待接单</text>
        </view>
        <view class="order-type" @click="goToOrderList(3)">
          <view class="icon-wrapper">
            <text class="uni-icons">🛵</text>
            <text class="badge" v-if="orderCounts.delivering > 0">{{ orderCounts.delivering }}</text>
          </view>
          <text class="type-name">配送中</text>
        </view>
        <!-- 评价功能暂时隐藏 -->
        <!-- <view class="order-type" @click="goToOrderList(4)">
          <view class="icon-wrapper">
            <text class="uni-icons">⭐</text>
          </view>
          <text class="type-name">待评价</text>
        </view> -->
      </view>
    </view>

    <!-- 功能列表 -->
    <view class="function-list">
      <view class="function-item" @click="goToAddress">
        <text class="uni-icons">📍</text>
        <text class="function-name">收货地址</text>
        <text class="arrow">></text>
      </view>
      <view class="function-item" @click="goToCoupon">
        <text class="uni-icons">🎟️</text>
        <text class="function-name">我的优惠券</text>
        <text class="arrow">></text>
      </view>
      <view class="function-item" @click="goToCouponReceive">
        <text class="uni-icons">🎁</text>
        <text class="function-name">领取优惠券</text>
        <text class="arrow">></text>
      </view>
      <view class="function-item" @click="goToPoints">
        <text class="uni-icons">🏆</text>
        <text class="function-name">我的积分</text>
        <text class="arrow">></text>
      </view>
      <view class="function-item" @click="goToFeedback">
        <text class="uni-icons">📝</text>
        <text class="function-name">意见反馈</text>
        <text class="arrow">></text>
      </view>
      <!-- <view class="function-item" @click="goToSettings">
        <text class="uni-icons">⚙️</text>
        <text class="function-name">设置</text>
        <text class="arrow">></text>
      </view> -->
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user.js'
import { getUserInfo } from '@/api/user.js'
import { getCouponList } from '@/api/coupon.js'
import { getOrderStatusCountList } from '@/api/order.js'
import { uploadToOSS, ensureStsTokenValid, fetchAndScheduleStsToken, clearStsTokenTimer } from '@/utils/oss'

// 响应式状态
const userInfo = ref({})
const couponCount = ref(0)
const orderCounts = reactive({
  pending: 0,
  processing: 0,
  delivering: 0
})
const availableCoupons = ref([])

// 昵称双向绑定
const nickname = ref('')
const originalNickname = ref('')

// 监听userInfo变化，同步昵称
watch(() => userInfo.value?.nickname, (newNickname) => {
  nickname.value = newNickname || ''
  originalNickname.value = newNickname || ''
}, { immediate: true })


/**
 * 获取用户信息
 */
const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    userInfo.value = data
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 如果获取失败，尝试从store获取
    const userStore = useUserStore()
    userInfo.value = userStore.userInfo || {}
  }
}

/**
 * 初始化数据
 */
const initData = async () => {
  // 获取用户信息
  await fetchUserInfo()

  // 获取可用优惠券数量
  try {
    const res = await getCouponList({ 
      status: 1
    })
    availableCoupons.value = res.data
  } catch (error) {
    console.error('获取优惠券失败:', error)
    availableCoupons.value = []
  }

  couponCount.value = availableCoupons.value.filter(coupon => coupon.status === 1).length

  // 获取各状态订单数量
  const orderStatusCountListRes = await getOrderStatusCountList()
  const orderStatusCountList = orderStatusCountListRes.data || []
  orderCounts.pending = orderStatusCountList.filter(order => order.status === 1)[0]?.count || 0
  orderCounts.processing = orderStatusCountList.filter(order => order.status === 2)[0]?.count || 0
  orderCounts.delivering = orderStatusCountList.filter(order => order.status === 3)[0]?.count || 0
}

/**
 * 跳转到订单列表页面
 * @param {number} [status] - 订单状态，可选
 */
const goToOrderList = (status) => {
  // 使用switchTab跳转到订单列表页面
  uni.switchTab({
    url: '/pages/order/list'
  })
  // 通过全局状态管理存储状态值，以便在订单列表页面获取
  if (status) {
    uni.setStorageSync('orderListStatus', status)
  }
}

/**
 * 跳转到地址列表
 */
const goToAddress = () => {
  uni.navigateTo({
    url: '/pages/address/manage'
  })
}

/**
 * 跳转到优惠券页面
 */
const goToCoupon = () => {
  uni.navigateTo({
    url: '/pages/user/coupon'
  })
}

/**
 * 跳转到优惠券领取页面
 */
const goToCouponReceive = () => {
  uni.navigateTo({
    url: '/pages/user/coupon-receive'
  })
}

/**
 * 跳转到积分页面
 */
const goToPoints = () => {
  uni.navigateTo({
    url: '/pages/user/points'
  })
}

/**
 * 跳转到反馈页面
 */
const goToFeedback = () => {
  uni.showToast({
    title: '反馈功能暂未开放',
    icon: 'none' 
  })
  return
  // uni.navigateTo({
  //   url: '/pages/user/feedback'
  // })
}

/**
 * 跳转到设置页面
 */
const goToSettings = () => {
  uni.navigateTo({
    url: '/pages/user/settings'
  })
}

/**
 * 选择头像回调
 */
const onChooseAvatar = async (e) => {
  const tempUrl = e.detail.avatarUrl
  try {
    uni.showLoading({ title: '上传中...' })
    await ensureStsTokenValid()
    const ossUrl = await uploadToOSS(tempUrl, 'avatars')
    userInfo.value.avatar = ossUrl
    const userStore = useUserStore()
    await userStore.updateUserInfo(userInfo.value)
    uni.showToast({ title: '头像更新成功', icon: 'success' })
  } catch (err) {
    console.error('头像上传失败:', err)
    uni.showToast({ title: '头像上传失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

/**
 * 昵称修改回调
 */
const onNicknameChange = async () => {
  if (nickname.value && nickname.value !== originalNickname.value) {
    try {
      // 更新userInfo中的昵称
      userInfo.value.nickname = nickname.value
      const userStore = useUserStore()
      await userStore.updateUserInfo(userInfo.value)
      // 更新成功后，更新原始昵称值
      originalNickname.value = nickname.value
      uni.showToast({ title: '昵称更新成功', icon: 'success' })
    } catch (err) {
      console.error('昵称更新失败:', err)
      // 失败时恢复原始昵称
      nickname.value = originalNickname.value
      uni.showToast({ title: '昵称更新失败', icon: 'none' })
    }
  }
}

// 页面挂载时初始化OSS Token
onMounted(() => {
  fetchAndScheduleStsToken()
})

// 页面卸载时清理定时器
onUnmounted(() => {
  clearStsTokenTimer()
})

// 页面显示时初始化数据
onShow(async () => {
  console.log('开始加载用户中心数据');
  
  await initData()
  
  // 检查用户信息是否完整，显示提示
  if (!userInfo.value.nickname || !userInfo.value.avatar) {
    uni.showModal({
      title: '提示',
      content: '请点击头像上传照片，点击昵称区域输入昵称，以便个性化展示',
      confirmText: '知道了',
      showCancel: false
    })
  }
})
</script>

<style lang="scss" scoped>
.content {
  min-height: 100vh;
  background-color: #ffffff;
  padding-bottom: 30rpx;
}

/* 用户信息卡片 */
.uni-card {
  margin: 30rpx;
  padding: 40rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(255, 107, 107, 0.2);
  position: relative;
  overflow: hidden;
}

/* 头像按钮 */
.avatar-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  border-radius: 50%;
  overflow: hidden;
}

/* 昵称输入框 */
.nickname-input {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
  padding: 0;
  margin: 0;
  min-height: 50rpx;
}

.uni-card {
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6rpx;
  }

  .uni-flex {
    &.uni-row {
      display: flex;
      align-items: center;

      .uni-avatar {
        width: 120rpx;
        height: 120rpx;
        border-radius: 50%;
        border: 4rpx solid rgba(255, 107, 107, 0.1);
        box-shadow: 0 4rpx 16rpx rgba(255, 107, 107, 0.1);
      }

      .uni-margin-left {
        margin-left: 24rpx;

        .uni-h4 {
          font-size: 36rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 8rpx;
          background: linear-gradient(to right, #333, #666);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }

        .uni-margin-top-sm {
          margin-top: 8rpx;
          display: flex;
          align-items: center;

          .uni-text-gray {
            font-size: 24rpx;
            color: #ff5e78;
            padding: 4rpx 12rpx;
            background: rgba(255, 107, 107, 0.1);
            border-radius: 20rpx;
            margin-right: 12rpx;

            &:last-child {
              background: rgba(25, 137, 250, 0.1);
              color: #1989fa;
            }
          }
        }
      }
    }

    &.uni-justify-around {
      margin-top: 40rpx;
      position: relative;
      justify-content: space-between;
      padding: 0 60rpx;

      &::before {
        content: '';
        position: absolute;
        top: -20rpx;
        left: 20%;
        right: 20%;
        height: 1rpx;
        background: linear-gradient(to right,
            transparent,
            rgba(255, 107, 107, 0.1) 20%,
            rgba(255, 107, 107, 0.1) 80%,
            transparent);
      }

      .uni-flex.uni-column {
        text-align: center;
        transition: transform 0.3s ease;

        &:active {
          transform: scale(0.95);
        }

        .uni-h4 {
          font-size: 40rpx;
          font-weight: 600;
          color: #ff6b6b;
          margin-bottom: 8rpx;
        }

        .uni-text-gray {
          font-size: 26rpx;
          color: #ff5e78;
        }
      }
    }
  }
}

/* 订单区域 */
.order-section {
  margin: 30rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.03);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      position: relative;
      padding-left: 20rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 6rpx;
        height: 28rpx;
        background: linear-gradient(to bottom, #ff9a9e, #ff6b6b);
        border-radius: 6rpx;
      }
    }

    .view-all {
      display: flex;
      align-items: center;
      color: #ff5e78;
      font-size: 26rpx;

      .arrow {
        margin-left: 8rpx;
        transition: transform 0.3s ease;
      }

      &:active .arrow {
        transform: translateX(4rpx);
      }
    }
  }

  .order-types {
    display: flex;
    justify-content: space-around;

    .order-type {
      text-align: center;
      transition: transform 0.3s ease;

      &:active {
        transform: scale(0.95);
      }

      .icon-wrapper {
        position: relative;
        width: 100rpx;
        height: 100rpx;
        margin: 0 auto 12rpx;

        .uni-icons {
          font-size: 56rpx;
          background: linear-gradient(135deg, #ff9a9e, #ff6b6b);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          filter: drop-shadow(0 2rpx 4rpx rgba(255, 107, 107, 0.2));
        }

        .badge {
          position: absolute;
          top: -8rpx;
          right: -8rpx;
          background: #ff6b6b;
          color: #fff;
          font-size: 22rpx;
          min-width: 32rpx;
          height: 32rpx;
          line-height: 32rpx;
          text-align: center;
          border-radius: 16rpx;
          padding: 0 6rpx;
          box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
        }
      }

      .type-name {
        font-size: 26rpx;
        color: #ff5e78;
      }
    }
  }
}

/* 功能列表 */
.function-list {
  margin: 30rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.03);
  overflow: hidden;

  .function-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    position: relative;
    transition: all 0.3s ease;

    &:active {
      background-color: rgba(0, 0, 0, 0.02);
    }

    &::after {
      content: '';
      position: absolute;
      left: 30rpx;
      right: 30rpx;
      bottom: 0;
      height: 1rpx;
      background: linear-gradient(to right,
          transparent,
          rgba(0, 0, 0, 0.05) 20%,
          rgba(0, 0, 0, 0.05) 80%,
          transparent);
    }

    &:last-child::after {
      display: none;
    }

    .uni-icons {
      font-size: 40rpx;
      margin-right: 20rpx;
      background: linear-gradient(135deg, #ff9a9e, #ff6b6b);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .function-name {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }

    .arrow {
      color: #ccc;
      font-size: 24rpx;
      transition: transform 0.3s ease;
    }

    &:active .arrow {
      transform: translateX(4rpx);
    }
  }
}
</style>